package com.carkeeper.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carkeeper.dto.EmployeeDTO;
import com.carkeeper.exception.BussinessException;
import com.carkeeper.mapper.EmployeeMapper;
import com.carkeeper.pojo.EmployeePO;
import com.carkeeper.service.EmployeeService;
import com.carkeeper.vo.EmployeeQueryParamVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @version : 1.0
 * @outhor : zwk
 * @data : Create in 2020-05-26
 * @description :
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /*
    保存或更新员工信息
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean saveAndUpdate(EmployeePO employeePO) {
        if (employeePO.getUsername() != null && employeePO.getUsername().equals("")) {
            employeePO.setUsername(null);
        }
        if (employeePO.getName() != null && employeePO.getName().equals("")) {
            employeePO.setName(null);
        }
        if (!StringUtils.isEmpty(employeePO.getPassword())) {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            employeePO.setPassword(passwordEncoder.encode(employeePO.getPassword()));
        }
        if (employeePO.getId() != null) {
            employeeMapper.updateById(employeePO);
        } else {
            employeeMapper.insert(employeePO);
        }
        return true;
    }

    /*
    删除 id
     */
    @Override
    public Boolean delete(Long id) {
        employeeMapper.deleteById(id);
        return true;
    }

    /*
    分页查
     */
    @Override
    public Page<EmployeePO> findByPage(EmployeeQueryParamVO paramVO) {
        if (paramVO.getPage() == null) {
            paramVO.setPage(1L);
        }
        if (paramVO.getPageSize() == null) {
            paramVO.setPageSize(10L);
        }
        Page<EmployeePO> page = new Page<>(paramVO.getPage(), paramVO.getPageSize());
        EmployeePO paramPO = new EmployeePO();
        BeanUtils.copyProperties(paramVO, paramPO);
        LambdaQueryWrapper<EmployeePO> lambdaQueryWrapper =
                buildWrapper(paramPO, null, paramVO.getHasUsername());
        return employeeMapper.selectPage(page, lambdaQueryWrapper);
    }

    /**
     * 删除
     *
     * @param id /*
     *           id 查
     */
    @Override
    public EmployeePO findById(Long id) {
        EmployeePO po = employeeMapper.selectById(id);
        po.setPassword(null);
        return po;
    }

    /*
       员工list
     */
    @Override
    public List<EmployeePO> list(EmployeeDTO employeeDTO) {
        EmployeePO paramsPO = new EmployeePO();
        BeanUtils.copyProperties(employeeDTO, paramsPO);
        LambdaQueryWrapper<EmployeePO> lambdaQueryWrapper = buildWrapper(paramsPO, employeeDTO.getIds(), employeeDTO.getHasUsername());
        return employeeMapper.selectList(lambdaQueryWrapper);
    }

    /**
     * 构建查询包装器
     *
     * @param employeePO
     * @param ids
     * @return
     */
    private LambdaQueryWrapper<EmployeePO> buildWrapper(EmployeePO employeePO, List<Long> ids, Boolean hasUsername) {
        LambdaQueryWrapper<EmployeePO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (ids != null && ids.size() > 0) {
            lambdaQueryWrapper.in(EmployeePO::getId, ids);
        }
        if (!StringUtils.isEmpty(employeePO.getUsername())) {
            lambdaQueryWrapper.like(EmployeePO::getUsername, employeePO.getUsername());
        }
        if (!StringUtils.isEmpty(employeePO.getPhone())) {
            lambdaQueryWrapper.like(EmployeePO::getPhone, employeePO.getPhone());
        }
        if (!StringUtils.isEmpty(employeePO.getEmail())) {
            lambdaQueryWrapper.like(EmployeePO::getEmail, employeePO.getEmail());
        }
        if (!StringUtils.isEmpty(employeePO.getDepartmentId())) {
            lambdaQueryWrapper.eq(EmployeePO::getDepartmentId, employeePO.getDepartmentId());
        }
        if (!StringUtils.isEmpty(employeePO.getAccountStatus())) {
            lambdaQueryWrapper.eq(EmployeePO::getAccountStatus, employeePO.getAccountStatus());
        }
        if (employeePO.getStatus() != null && employeePO.getStatus() > 0) {
            lambdaQueryWrapper.eq(EmployeePO::getStatus, employeePO.getStatus());
        }
        if (!StringUtils.isEmpty(employeePO.getName())) {
            lambdaQueryWrapper.like(EmployeePO::getName, employeePO.getName());
        }
        if (!StringUtils.isEmpty(employeePO.getPassword())) {
            lambdaQueryWrapper.eq(EmployeePO::getPassword, employeePO.getPassword());
        }
        if (StringUtils.isEmpty(employeePO.getUsername())&&hasUsername != null) {
            if (hasUsername) {
                lambdaQueryWrapper.isNotNull(EmployeePO::getUsername);
            } else {
                lambdaQueryWrapper.isNull(EmployeePO::getUsername);
            }
        }
        lambdaQueryWrapper.orderByDesc(EmployeePO::getCreateTime);
        return lambdaQueryWrapper;
    }

    /**
     * 校验账号密码
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public EmployeePO login(String username, String password) {
        EmployeePO em = new EmployeePO();
        em.setUsername(username);

        QueryWrapper<EmployeePO> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(EmployeePO::getUsername, username);
        //从数据库查询出的对象
        EmployeePO employeePO = employeeMapper.selectOne(wrapper);
        if (employeePO == null) {
            //如果数据库中查询到的用户对象为空, 则返回登录失败
            throw new BussinessException("用户不存在!!!");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//        if (employeePO.getPassword().equals(passwordEncoder.encode(password))) {
        if (passwordEncoder.matches(password,employeePO.getPassword())) {
            return employeePO;
        }
        throw new BussinessException("密码错误!");
    }

    /**
     * 根据id返回用户
     *
     * @param id
     * @return
     */
    @Override
    public EmployeePO loadUserById(Long id) {
        QueryWrapper<EmployeePO> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(EmployeePO::getId, id);
        EmployeePO employeePO = employeeMapper.selectById(id);
        return employeePO;
    }

    @Override
    public EmployeePO loadUserByUsername(String username) {
        QueryWrapper<EmployeePO> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(EmployeePO::getUsername, username);
        return employeeMapper.selectOne(wrapper);
    }

    @Override
    public List<EmployeePO> getUserListByIds(List<Long> ids) {
        List<EmployeePO> results = employeeMapper.selectBatchIds(ids);
        if (results == null) {
            return new ArrayList<EmployeePO>();
        }
        return employeeMapper.selectBatchIds(ids);
    }


}
